package com.xywy.bloodandroid.act;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.xywy.bloodandroid.R;
import com.xywy.bloodandroid.base.BaseActivity;
import com.xywy.bloodandroid.bean.BloodPressureData;
import com.xywy.bloodandroid.bean.BloodPresureDataFromServer;
import com.xywy.bloodandroid.bean.User;
import com.xywy.bloodandroid.dao.BaseDao;
import com.xywy.bloodandroid.dao.BloodPressureDataDao;
import com.xywy.bloodandroid.dao.BloodPressureDataDao.Properties;
import com.xywy.bloodandroid.fragment.BloodFragment;
import com.xywy.bloodandroid.util.MD5;
import com.xywy.bloodandroid.util.ObserverConstants;
import com.xywy.bloodandroid.util.UIUtil;
import com.xywy.bloodandroid.vollery.OnVolleyResponseListener;
import com.xywy.bloodandroid.vollery.PostRequest;

import de.greenrobot.dao.query.QueryBuilder;

/*******************************************
 * @Title: DataRecordActivity.java
 * @Package com.xywy.bloodandroid.act
 * @Description: TODO数据记录
 * @author Benwolf
 * @date 2014-12-26 上午9:45:16
 * @version V1.0
 ********************************************/
public class DataRecordActivity extends BaseActivity {
	private RelativeLayout left_img;
	private TextView middle_title;
	private TextView tv_date;
	private TextView tv_time;
	private EditText et_device;
	private EditText et_heigh_pressure;
	private EditText et_low_pressure;

	private Button btn_upload;

	private BloodPressureDataDao bloodDao;

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	SharedPreferences sp;

	String userid = null;
	private Editor editor;
	
	private OnDateSetListener mDateSetListener = new OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int month, int day) {
			month = month + 1;
			if (month < 10) {
				tv_date.setText(year + "-0" + month + "-" + day);
			} else {
				tv_date.setText(year + "-" + month + "-" + day);
			}

		}
	};
	private RelativeLayout rl_time;
	private OnTimeSetListener mTimeSetListener = new OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			tv_time.setText(hourOfDay + ":" + minute);
		}
	};

	@Override
	protected void initView(Bundle savedInstanceState) {
		setContentView(R.layout.activity_data_record);
		left_img = (RelativeLayout) findViewById(R.id.left_img);
		middle_title = (TextView) findViewById(R.id.middle_title);
		middle_title.setText(R.string.data_record_str);
		tv_date = (TextView) findViewById(R.id.tv_date);
		rl_time = (RelativeLayout) findViewById(R.id.rl_time);
		tv_time = (TextView) findViewById(R.id.tv_time);
		btn_upload = (Button) findViewById(R.id.btn_upload);
		et_device = (EditText) findViewById(R.id.et_device);
		et_heigh_pressure = (EditText) findViewById(R.id.et_heigh_pressure);
		et_low_pressure = (EditText) findViewById(R.id.et_low_pressure);

		tv_date.setText(sdf.format(new Date(System.currentTimeMillis())));
		Calendar calendar = Calendar.getInstance();
		tv_time.setText(calendar.get(Calendar.HOUR_OF_DAY) + ":"
				+ calendar.get(Calendar.MINUTE));
		
		sp = getSharedPreferences("config", Context.MODE_PRIVATE);
		editor = sp.edit();
		userid = User.getInstance(this).getUserid();
	}

	@Override
	protected void initListener() {
		// TODO Auto-generated method stub
		left_img.setOnClickListener(this);
		rl_time.setOnClickListener(this);
		btn_upload.setOnClickListener(this);
	}

	@Override
	protected void initData() {
		BaseDao baseDao = BaseDao.getInstance(this);
		bloodDao = baseDao.getBloodPressureDataDao();
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.left_img:
			finish();
			break;
		case R.id.rl_time:
			showTimePickerDialog();
			break;
		case R.id.btn_upload:
			check();
			break;
		default:
			break;
		}
	}

	private void showTimePickerDialog() {
		Calendar c = Calendar.getInstance();
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		TimePickerDialog timePicker = new TimePickerDialog(this,
				mTimeSetListener, hour, minute, true);
		timePicker.show();

	}

	public void showDatePickerDialog(View v) {
		System.out.println("showDatePickerDialog---");
		Calendar c = Calendar.getInstance();
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH);
		int mDay = c.get(Calendar.DAY_OF_MONTH);
		DatePickerDialog dialog = new DatePickerDialog(this, mDateSetListener,
				mYear, mMonth, mDay);
		dialog.show();

	}

	// private String secret_key = "2CV3aBc$l;@";

	private void uploadDataToServer(BloodPressureData data) {
		String userid = User.getInstance(this).getUserid();
		if (userid == null || "".equals(userid)) {
			showToast("请先登录");
			return;
		}
		bloodDao.insert(blood_data);
		finish();
		getContentResolver().notifyChange(ObserverConstants.CHANGE_BLOOD, null);
	}

	/**
	 * 将数据库中提取出来的数据转换成服务器的been
	 * 
	 * @param data
	 */
	private String turn2ServerJsonData(BloodPressureData data, String userID) {
		Gson gson = new Gson();
		BloodPresureDataFromServer dataFormServer = new BloodPresureDataFromServer();
		dataFormServer.setApp_data(data.getDevice_id());
		dataFormServer.setApp_user_id("");
		dataFormServer.setDatatime(data.getDate());// 时间上面已经处理
		dataFormServer.setHeart(data.getHeartRate());
		dataFormServer.setHigh(data.getHighPressure());
		dataFormServer.setLow(data.getLowPressure());
		dataFormServer.setShou_data(data.getHand_str());
		dataFormServer.setXywy_userid(userID);
		return gson.toJson(dataFormServer);
	}

	BloodPressureData blood_data;

	public void check() {
		String date = tv_date.getText().toString().trim();
		String time = tv_time.getText().toString().trim();
		String device_str = et_device.getText().toString().trim();
		String heigh_str = et_heigh_pressure.getText().toString().trim();
		String low_str = et_low_pressure.getText().toString().trim();
		float pressure_heigh = 0;
		float pressure_low = 0;
		if (date == null || "".equals(date)) {
			showToast("请选择日期");
			return;
		} else if (time == null || "".equals(time)) {
			showToast("请选择具体时间");
			return;
		} else if (device_str == null || "".equals(device_str)) {
			showToast("请填写设备名称");
			return;
		} else if (heigh_str == null || "".equals(heigh_str)) {
			showToast("请填写高压");
			return;
		} else if (low_str == null || "".equals(low_str)) {
			showToast("请填写低压");
			return;
		}
		pressure_heigh = Float.parseFloat(heigh_str);
		pressure_low = Float.parseFloat(low_str);

		if (pressure_heigh < 30 || pressure_heigh > 200) {
			showToast("高压范围30--200");
			return;
		}

		if (pressure_low < 30 || pressure_low > 200) {
			showToast("低压范围30--200");
			return;
		}

		if (pressure_low >= pressure_heigh) {
			showToast("高压值应大于低压值");
			return;
		}
		try {
			String str = tv_date.getText().toString() + " "
					+ tv_time.getText().toString();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
			Date dateT = sf.parse(str);
			System.out.println("time----" + dateT.getTime());
			BloodPressureData data = new BloodPressureData(null, 0f,
					pressure_heigh, pressure_low, "State",
					"temp_automactily_device_identify",
					"temp_handly_device_identify", dateT.getTime());
			blood_data = data.clone();
			uploadDataToServer(data);
			uploadDataToServer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	private final String sort = "xueya";
	private String URL_UPLOAD = "http://api.yun.xywy.com/index.php/api/setdata/data_all/";

	private void uploadDataToServer() {
		// data.setDate(data.getDate() / 1000);
		System.out.println("uploadDataToServer----");
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("app_username", "xywy_tizhong");
		try {
			String userid = User.getInstance(this).getUserid();
		} catch (Exception e) {
			// TODO: handle exception
		}

		if (userid == null || "".equals(userid)) {
			return;
		}
		params.put("xywy_userid", userid);
		params.put("sort", sort);
		// -------------------
		final List<BloodPressureData> pressuerDatas = getUnuploadData();
		String dataStr = turn2ServerJsonData(pressuerDatas, userid);
		params.put("data", dataStr);
		System.out.println("data---str----" + dataStr);
		params.put("datatime", System.currentTimeMillis() / 1000 + "");
		// -------------------
		String sn = BloodFragment.SECRETKEY_WEIGHT_SCALEF + userid + sort
				+ dataStr + "xywy_tizhong";
		try {
			params.put("sn", MD5.md5s(sn));
		} catch (Exception e) {
			e.printStackTrace();
		}

		PostRequest<String> post = new PostRequest<String>(URL_UPLOAD,
				String.class, new OnVolleyResponseListener<String>() {

					@Override
					public void onError(VolleyError volleyError) {
						volleyError.printStackTrace();
						UIUtil.DissDialog(DataRecordActivity.this, waittingDialog);
					}

					@Override
					public void onSuccess(String response) {
						UIUtil.DissDialog(DataRecordActivity.this, waittingDialog);
						if (response == null) {
							return;
						}
						try {
							JSONObject json = new JSONObject(response);
							int status = json.optInt("status");
							if (status == 0) {
								// bloodDao.insert(blood_data);
								// 将数据保存之后，获取最后一条的时间来替换本地数据；
								editor.putLong(
										"last_download_blood_presure_time",
										(long) (pressuerDatas.get(pressuerDatas
												.size() - 1).getDate()))
										.commit();
								// showToast("上传成功");
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						System.out.println("------------" + response);
					}
				});
		post.setIsParseJson(false);
		post.setParams(params);
		System.out.println(params);
		executeRequest(post);
	}

	/**
	 * 获得需要上传的数据
	 * 
	 * @return
	 */
	public List<BloodPressureData> getUnuploadData() {
		long lastSaveTime = sp
				.getLong("last_download_blood_presure_time", 1000); // 最后的上传时间
		Log.e("time---", lastSaveTime + "");
		QueryBuilder<BloodPressureData> qb = bloodDao.queryBuilder();
		qb.orderAsc(Properties.Date).where(Properties.Date.gt(lastSaveTime));
		Log.e("upload", "血压： 从本地获取需要上传的数据: " + qb.list().size());
		return qb.list();
	}

	/**
	 * 将数据库中提取出来的数据转换成服务器的been
	 * 
	 * @param data
	 */
	private String turn2ServerJsonData(List<BloodPressureData> datas,
			String userID) {
		Gson gson = new Gson();
		List<BloodPresureDataFromServer> bloodServers = new ArrayList<BloodPresureDataFromServer>();
		for (BloodPressureData data : datas) {
			BloodPresureDataFromServer dataFormServer = new BloodPresureDataFromServer();
			dataFormServer.setApp_data(data.getDevice_id());
			dataFormServer.setApp_user_id("");
			dataFormServer.setDatatime(data.getDate() / 1000);// 时间上面已经处理
			dataFormServer.setHeart(data.getHeartRate());
			dataFormServer.setHigh(data.getHighPressure());
			dataFormServer.setLow(data.getLowPressure());
			dataFormServer.setShou_data(data.getHand_str());
			dataFormServer.setXywy_userid(userID);
			bloodServers.add(dataFormServer);
		}
		return gson.toJson(bloodServers);
	}

}
